package model

import (
	"reflect"
	"sync"
)

type Register struct {
	Models sync.Map
	mu     sync.RWMutex
}

func (r *Register) Get(t any) *Model {
	typ := reflect.TypeOf(t)
	a := typ.Kind()
	if a != reflect.Pointer {
		panic("register model must be a pointer")
	}
	typ = typ.Elem()

	name := typ.Name()
	r.mu.RLock()
	m, ok := r.Models.Load(name)
	r.mu.RUnlock()
	if ok {
		return m.(*Model)
	}

	ml := &Model{}
	ml.parseModel(t)

	r.mu.Lock()
	r.Models.Store(name, ml)
	r.mu.Unlock()
	return ml
}
